package com.xzjt.web.service.impl;

import cn.hutool.json.JSONObject;

import com.xzjt.common.components.RedisService;
import com.xzjt.common.exception.CustomException;
import com.xzjt.web.entity.SysUser;
import com.xzjt.web.config.JwtService;
import com.xzjt.web.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @ClassName: LoginServiceImpl
 * @Author: yuandong
 * @Date 2021/10/9 15:52
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private JwtService jwtService;


    @Override
    public String createToken(SysUser user) {
        long tokenExpireTime = 1;//登录有效期 一分钟
        String token = jwtService.generate(user.getUsername());
        JSONObject obj = new JSONObject();
        obj.put("user", user);
        // 将token放入缓存
        boolean flag = redisService.set(token, user, tokenExpireTime);
        //成功生成token,并且成功保存到redis才 返回该token;
        if(flag){
            return token;
        }else{
           throw new CustomException("999","后端缓存错误！");
        }

    }
}
